// 从server拿到指定邮件的全部信息
char *getDetail(int sock, int choice);
char rec[4096];
int download(int sock);

char *getDetail(int sock, int choice)
{
    char buf[] = "RETR ";
    char msg[8];
    bzero(rec, strlen(rec));
    sprintf(msg, "%s%d", buf, choice);

    strcat(msg, "\r\n");

    // enter command
    int m = write(sock, msg, strlen(msg));

    bzero(msg, strlen(msg));
    bzero(buf, strlen(buf));
    // printf("origin length: %zu\n\n", strlen(rec));
    int n = read(sock, rec, sizeof(rec));
    // 当收到的文件不对劲——我尝试过用do..while但是不行
    while (strlen(rec) < 800)
    {
        // printf("\ndevided into 2 messages\n");
        // 再read一次socket上的值
        char rec2[4096];
        n = read(sock, rec2, sizeof(rec2));
        // 把新的放旧的的后面
        strcat(rec, rec2);
        bzero(rec2, strlen(rec2));
        // printf("new length: %zu\n\n", strlen(rec));
    }
    // printf("%s\n", rec);

    return rec;
}

int download(int sock)
{
    char *recTemp;
    int resp;
    printf("Which email to download and delete from cloud: \n");
    scanf("%d", &resp);
    CLEAR_BUF
    if (resp>listNum(sock)||listNum<=0)
    {
        perror("Input illegal");
        return 1;
    }
    recTemp = getDetail(sock, resp);
    char buf[] = "../mail/";
    char end[] = ".eml";
    char buff[15];
    sprintf(buff,"%s%d%s",buf,resp,end);

    FILE *fp = NULL;
    
    fp = fopen(buff, "w");
    if (fputs(recTemp, fp)!=EOF)
    {
        printf("Downloaded Sucessfully\n\n");
        fclose(fp);
        bzero(buff,strlen(buff));
        sprintf(buff, "dele %d\r\n", resp);
        
        if ((write(sock, buff, strlen(buff)))>0)
        {
            printf("Deleted Sucessfully\n");
            return 0;
        }
        return 1;
                
    }
    else{
        fclose(fp);
        return 1;
    }
    
}
